//
//  CYLTabBarControllerConfig.m
//  CYLTabBarController
//
//  v1.16.0 Created by 微博@iOS程序犭袁 ( http://weibo.com/luohanchenyilong/ ) on 10/20/15.
//  Copyright © 2015 https://github.com/ChenYilong . All rights reserved.
//
#import "CYLTabBarControllerConfig.h"
#import <UIKit/UIKit.h>

static CGFloat const CYLTabBarControllerHeight = 40.f;

@interface CYLBaseNavigationController : UINavigationController

@end

@implementation CYLBaseNavigationController

- (void)viewDidLoad{
    [super viewDidLoad];
    self.navigationBar.barTintColor = UCMBlackColor;
    self.navigationBar.tintColor = UCMWhiteColor;
    [self.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName :UCMWhiteColor, NSFontAttributeName : [UIFont systemFontOfSize:18]}];
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if (self.viewControllers.count > 0) {
        viewController.hidesBottomBarWhenPushed = YES;
    }
    [super pushViewController:viewController animated:animated];
}

@end

//View Controllers
#import "CMHomeViewController.h"
#import "CMStockViewController.h"
#import "CMSaleViewController.h"
#import "CMStatisticViewController.h"
#import "CMMineViewController.h"

@interface CYLTabBarControllerConfig ()<UITabBarControllerDelegate>

@property (nonatomic, readwrite, strong) CYLTabBarController *tabBarController;

@end

@implementation CYLTabBarControllerConfig

/**
 *  lazy load tabBarController
 *
 *  @return CYLTabBarController
 */
- (CYLTabBarController *)tabBarController {
    if (_tabBarController == nil) {
        /**
         * 以下两行代码目的在于手动设置让TabBarItem只显示图标，不显示文字，并让图标垂直居中。
         * 等效于在 `-tabBarItemsAttributesForController` 方法中不传 `CYLTabBarItemTitle` 字段。
         * 更推荐后一种做法。
         */
        UIEdgeInsets imageInsets = UIEdgeInsetsZero;//UIEdgeInsetsMake(4.5, 0, -4.5, 0);
        UIOffset titlePositionAdjustment = UIOffsetZero;//UIOffsetMake(0, MAXFLOAT);
        
        CYLTabBarController *tabBarController = [CYLTabBarController tabBarControllerWithViewControllers:self.viewControllers
                                                                                   tabBarItemsAttributes:self.tabBarItemsAttributesForController
                                                                                             imageInsets:imageInsets
                                                                                 titlePositionAdjustment:titlePositionAdjustment
                                                 context:self.context
                                                 ];
        [self customizeTabBarAppearance:tabBarController];
        _tabBarController = tabBarController;
    }
    return _tabBarController;
}

- (NSArray *)viewControllers {
    CMHomeViewController *homeVC = [[CMHomeViewController alloc]init];
    UIViewController *homeNavigationController = [[CYLBaseNavigationController alloc]
                                                  initWithRootViewController:homeVC];
    CMStockViewController *stockVC = [[CMStockViewController alloc]initWithNibName:@"CMStockViewController" bundle:[NSBundle mainBundle]];
    stockVC.title = @"库存";
    UIViewController *stockNavigationController = [[CYLBaseNavigationController alloc]
                                                  initWithRootViewController:stockVC];
    CMSaleViewController *saleVC = [[CMSaleViewController alloc]initWithNibName:@"CMSaleViewController" bundle:[NSBundle mainBundle]];
    saleVC.title = @"销售";
    UIViewController *saleVCNavigationController = [[CYLBaseNavigationController alloc]
                                                   initWithRootViewController:saleVC];
    CMStatisticViewController *statisticVC = [[CMStatisticViewController alloc]initWithNibName:@"CMStatisticViewController" bundle:[NSBundle mainBundle]];
    statisticVC.title = @"统计";
    UIViewController *statisticNavigationController = [[CYLBaseNavigationController alloc]
                                                    initWithRootViewController:statisticVC];
    CMMineViewController *mineVC = [[CMMineViewController alloc]initWithNibName:@"CMMineViewController" bundle:[NSBundle mainBundle]];
    mineVC.title = @"我的";
    UIViewController *mineNavigationController = [[CYLBaseNavigationController alloc]
                                                       initWithRootViewController:mineVC];
    
    
  
    NSArray *viewControllers = @[
                                 homeNavigationController,
                                 stockNavigationController,
                                 saleVCNavigationController,
                                 statisticNavigationController,
                                 mineNavigationController
                                 ];
    return viewControllers;
}

- (NSArray *)tabBarItemsAttributesForController {
    NSDictionary *firstTabBarItemsAttributes = @{
                                                 CYLTabBarItemTitle : @"首页",
                                                 CYLTabBarItemImage : @"tab_home_unselected",
                                                 CYLTabBarItemSelectedImage : [UIImage imageNamed:@"tab_home_selected"],
                                                 };
    NSDictionary *secondTabBarItemsAttributes = @{
                                                  CYLTabBarItemTitle : @"库存",
                                                  CYLTabBarItemImage : @"tab_stock_unselected",
                                                  CYLTabBarItemSelectedImage : [UIImage imageNamed:@"tab_stock_selected"],
                                                  
                                                  };
    NSDictionary *thirdTabBarItemsAttributes = @{
                                                 CYLTabBarItemTitle : @"销售",
                                                 CYLTabBarItemImage : @"tab_sales_unselected",
                                                 CYLTabBarItemSelectedImage : [UIImage imageNamed:@"tab_sales_selected"],
                                                                                                  };
    NSDictionary *fourthTabBarItemsAttributes = @{
                                                  CYLTabBarItemTitle : @"统计",
                                                  CYLTabBarItemImage : @"tab_statistic_unselected",
                                                  CYLTabBarItemSelectedImage : [UIImage imageNamed:@"tab_statistic_selected"],
                                                  
                                                  };
    NSDictionary *fifthTabBarItemsAttributes = @{
                                                                                            CYLTabBarItemTitle : @"我的",
                                                  CYLTabBarItemImage : @"tab_mine_unselected",
                                                  CYLTabBarItemSelectedImage : [UIImage imageNamed:@"tab_mine_selected"],
                                                  };

    NSArray *tabBarItemsAttributes = @[
                                       firstTabBarItemsAttributes,
                                       secondTabBarItemsAttributes,
                                       thirdTabBarItemsAttributes,
                                       fourthTabBarItemsAttributes,
                                       fifthTabBarItemsAttributes
                                       ];
    return tabBarItemsAttributes;
}

/**
 *  更多TabBar自定义设置：比如：tabBarItem 的选中和不选中文字和背景图片属性、tabbar 背景图片属性等等
 */
- (void)customizeTabBarAppearance:(CYLTabBarController *)tabBarController {
    tabBarController.tabBar.barTintColor = UCMBlackColor;
    [tabBarController setTintColor:UCMMainTabBarSelectedColor];
    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:UCMMainTabBarUnSelectedColor, NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];
    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:UCMMainTabBarSelectedColor, NSForegroundColorAttributeName, nil] forState:UIControlStateSelected];
}

- (void)updateTabBarCustomizationWhenTabBarItemWidthDidUpdate {
    void (^deviceOrientationDidChangeBlock)(NSNotification *) = ^(NSNotification *notification) {
        UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
        if ((orientation == UIDeviceOrientationLandscapeLeft) || (orientation == UIDeviceOrientationLandscapeRight)) {
            NSLog(@"Landscape Left or Right !");
        } else if (orientation == UIDeviceOrientationPortrait) {
            NSLog(@"Landscape portrait!");
        }
        [self customizeTabBarSelectionIndicatorImage];
    };
    [[NSNotificationCenter defaultCenter] addObserverForName:CYLTabBarItemWidthDidChangeNotification
                                                      object:nil
                                                       queue:[NSOperationQueue mainQueue]
                                                  usingBlock:deviceOrientationDidChangeBlock];
}

- (void)customizeTabBarSelectionIndicatorImage {
    ///Get initialized TabBar Height if exists, otherwise get Default TabBar Height.
    CGFloat tabBarHeight = CYLTabBarControllerHeight;
    CGSize selectionIndicatorImageSize = CGSizeMake(CYLTabBarItemWidth, tabBarHeight);
    //Get initialized TabBar if exists.
    UITabBar *tabBar = [self cyl_tabBarController].tabBar ?: [UITabBar appearance];
    [tabBar setSelectionIndicatorImage:
     [[self class] imageWithColor:[UIColor yellowColor]
                             size:selectionIndicatorImageSize]];
}

+ (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize {
    CGSize size = CGSizeMake([UIScreen mainScreen].bounds.size.width * scaleSize, image.size.height * scaleSize);
    UIGraphicsBeginImageContextWithOptions(size, NO, 1.0);
    [image drawInRect:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    if (!color || size.width <= 0 || size.height <= 0) return nil;
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width + 1, size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
